<template>
  <y-dialog
    v-model="dialogVisible"
    :title="isCreate ? '新增角色' : '编辑角色'"
    @before-show="handleDialogOpen"
  >
    <q-form ref="formRef" @submit.prevent="submitForm" class="q-gutter-y-md">
      <q-input
        v-model.trim="form.name"
        label="角色名称 *"
        :rules="rules.name"
        outlined
        dense
        lazy-rules
        :disable="loading"
      />

      <q-input
        v-model.trim="form.key"
        label="角色标识 *"
        :rules="rules.key"
        outlined
        dense
        lazy-rules
        :disable="loading"
      />

      <q-input
        v-model.number="form.sort"
        label="显示排序"
        type="number"
        :rules="rules.sort"
        outlined
        dense
        :disable="loading"
      />

      <div class="q-mt-sm">
        <q-toggle
          v-model="form.status"
          label="状态"
          true-value="0"
          false-value="1"
          checked-icon="check"
          unchecked-icon="clear"
          color="primary"
          :disable="loading"
        />
      </div>

      <q-input
        v-model.trim="form.remark"
        label="备注"
        type="textarea"
        outlined
        rows="3"
        :disable="loading"
      />

      <div class="flex justify-end q-gutter-sm q-mt-md">
        <q-btn label="取消" v-close-popup flat color="grey-7" :disable="loading" />
        <q-btn
          label="重置"
          type="reset"
          flat
          color="grey-7"
          @click="resetForm"
          :disable="loading"
        />
        <q-btn
          type="submit"
          :label="isCreate ? '创建' : '保存'"
          color="primary"
          :loading="loading"
          unelevated
        />
      </div>
    </q-form>
  </y-dialog>
</template>

<script setup>
import modal from '@/plugins/modal'
import { addRole, getRole, updateRole } from '@/api/sys/role'
// 组件属性与事件
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  roleId: { type: String, default: undefined },
  operate: {
    type: String,
    default: 'create',
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

// 状态管理
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const loading = ref(false)
const formRef = ref(null)
const isCreate = computed(() => props.operate === 'create')

// 表单配置
const initialFormState = {
  id: null,
  name: '',
  key: '',
  sort: 0,
  status: '0',
  remark: '',
}

const form = reactive({ ...initialFormState })

const rules = {
  name: [
    (val) => !!val?.trim() || '角色名称不能为空',
    (val) => val.length <= 50 || `名称长度不能超过 50 个字符`,
  ],
  key: [
    (val) => !!val?.trim() || '角色标识不能为空',
    (val) => /^[a-zA-Z0-9_:]+$/.test(val) || '只能包含字母、数字、下划线和冒号',
  ],
  sort: [(val) => val >= 0 || '排序必须大于等于0', (val) => Number.isInteger(val) || '必须为整数'],
}

// 对话框操作
const handleDialogOpen = async () => {
  if (isCreate.value) {
    resetForm()
    return
  }

  if (!props.roleId) {
    modal.msgError('缺少角色ID')
    dialogVisible.value = false
    return
  }

  try {
    loading.value = true
    const { data } = await getRole(props.roleId)
    Object.assign(form, data)
  } catch (error) {
    modal.msgError('加载角色信息失败')
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

// 表单重置
const resetForm = () => {
  Object.assign(form, initialFormState)
  formRef.value?.resetValidation?.()
}

// 提交表单
const submitForm = async () => {
  try {
    const isValid = await formRef.value.validate()
    if (!isValid) return

    loading.value = true
    const payload = { ...form }

    await (isCreate.value ? addRole(payload) : updateRole(payload))
    modal.msgSuccess(`${isCreate.value ? '创建' : '更新'}成功`)
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    modal.msgError(`${isCreate.value ? '创建' : '更新'}失败`)
  } finally {
    loading.value = false
  }
}
</script>
